# (C) 2019, Chen Xiao <chen_xiao@bosc.cn>
# (C) 2019, Internal Use

from __future__ import (absolute_import, division, print_function)

__metaclass__ = type

import time
import os
import shutil
import json
from ansible.plugins.callback import CallbackBase

DOCUMENTATION = '''
    callback: script_to_file
    type: notification
    requirements:
      - whitelist in configuration
    short_description: load system check result to file
    description:
        - This callback load system check result to file
'''

cache_dir = '/tmp/scripts_facts'


class FileHandler():
    def __init__(self):
        if os.path.isdir(cache_dir):
            shutil.rmtree(cache_dir)
            os.mkdir(cache_dir)

    def write(self, file, line):
        file = os.path.join(cache_dir, file)
        with open(file, 'a') as f:
            f.write(str(line))


class CallbackModule(CallbackBase):
    CALLBACK_VERSION = 2.0
    CALLBACK_TYPE = 'notification'
    CALLBACK_NAME = 'script_to_file'
    CALLBACK_NEEDS_WHITELIST = True

    def __init__(self):
        super(CallbackModule, self).__init__()
        self.check_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        self.task_tag = 'script_to_file'
        self.task_actions = ['command', 'shell', 'script', 'win_command', 'win_shell', 'set_fact', 'debug']
        self.file_handler = FileHandler()

    def load(self, result):

        host = result._host.get_name()
        hostvar = self.play._variable_manager._hostvars.get(host)
        hostname = hostvar.get('ansible_hostname', '')
        item = result.task_name
        rc = result._result.get('rc', -1)
        stdout = json.dumps(hostvar.get('shell_stdout'))
        check_tag = hostvar.get('checktag', '')
        if hostvar.get('ansible_system') == 'Linux':
            ip = hostvar.get('ansible_default_ipv4', {}).get('address', host)
        elif hostvar.get('ansible_system') == 'Win32NT':
            ip = hostvar.get('ansible_ip_addresses', [host])[0]
        else:
            ip = host

        self.file_handler.write(ip, stdout)
        self._display.display('Script to File: "%s", "%s", "%s", "%s", "%s", "%s", "%s"' % (
            ip, hostname, item, rc, stdout, self.check_time, check_tag))

    def v2_runner_on_failed(self, result, ignore_errors=False):
        if self.task_tag in result._task.tags and result._task.action in self.task_actions:
            self.load(result)

    def v2_runner_on_ok(self, result):
        if self.task_tag in result._task.tags and result._task.action in self.task_actions:
            self.load(result)

    def v2_runner_on_skipped(self, result):
        if self.task_tag in result._task.tags:
            result._result['rc'] = -2
            result._result['stdout'] = 'Skipped: %s' % result._result.get('skip_reason')
            self.load(result)

    def v2_runner_on_unreachable(self, result):
        if result._task.action == 'setup':
            result._result['rc'] = -1
            result._result['stdout'] = 'Error: Server was unreachable'
            self.load(result)

    def v2_playbook_on_play_start(self, play):
        self.play = play
